package com.lxq.dataStructure.linkList;


public class linkList<E> {
    //定义链表节点
    private class LNode<E>{
        //节点数据
        private E data;
        //指向下一节点
        private LNode<E> next;

        public LNode() {
            this.data = null;
            this.next = null;
        }

        public LNode(E data) {
            this.data = data;
            this.next = null;
        }

        @Override
        public String toString() {
            return "LNode:["+data+","+next+"]";
        }
    }
    //链表元素个数
    private int size;
    //头指针
    private LNode<E> head;
    //指向尾结点的引用
    private LNode<E> lastNode;

    public void initLinkList(){
        //定义头结点
        LNode<E> headNode= new LNode<>();
        this.size = 0;
        this.head = headNode;
        this.lastNode = headNode;

    }

    //头插法
    public void addHead(E data){
        LNode<E> node = new LNode<>(data);
        if (this.head==this.lastNode){
            this.lastNode = node;
        }
        node.next = head.next;
        head.next = node;
        size++;
    }

    //尾插法
    public void addLast(E data){
        LNode<E> node = new LNode<>(data);
        lastNode.next = node;
        this.lastNode = node;
        size++;
    }

    //删除节点
    public void delete(E data){
        LNode<E> preNode= head;

        for (LNode<E> node = head.next;node!=null;node=node.next){
            if (node.data.equals(data)){
                if (node==this.lastNode){
                    this.lastNode = preNode;
                }
                preNode.next = node.next;
                size--;
            }else{
                preNode = preNode.next;
            }

        }

    }
    public void deleteHead(){
        delete(head.next.data);
    }
    public void deleteLast(){
        delete(lastNode.data);
    }

    //修改某节点的值
    public boolean update(E point,E data){
        LNode<E> node = find(point);
        if (node!=null){
            node.data = data;
            return true;
        }else{
            return false;
        }
    }

    //遍历查询
    public LNode<E> find(E data){
        for (LNode<E> node = head.next;node!=null;node=node.next){
            if (node.data.equals(data)){
                return node;
            }
        }
        return null;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(String.format("linkList:size=%d%n",size));
        sb.append("[");
        for(LNode<E> point = head.next ; point!=null ; point = point.next){
            sb.append(point.data).append(" -> ");
        }
        if (size==0){
            sb.append("]");
        }else{
            sb.replace(sb.length()-4,sb.length(),"]");
        }
        return sb.toString();
    }
}
